<template>
  <div class="lingma-chat-container">
    <el-card class="chat-card">
      <template #header>
        <div class="card-header">
          <span>通义灵码助手</span>
          <el-button 
            type="primary" 
            @click="clearChat"
            :icon="Delete"
            circle
            size="small"
          ></el-button>
        </div>
      </template>
      
      <div class="chat-messages" ref="chatContainer">
        <div 
          v-for="(message, index) in messages" 
          :key="index"
          :class="['message', message.role]"
        >
          <div class="message-content">
            <div class="avatar">
              <el-avatar 
                :icon="message.role === 'user' ? 'User' : 'MagicStick'" 
                size="small"
              />
            </div>
            <div class="content">
              <div class="text" v-html="formatMessage(message.content)"></div>
            </div>
          </div>
        </div>
        <div v-if="loading" class="message assistant">
          <div class="message-content">
            <div class="avatar">
              <el-avatar icon="MagicStick" size="small" />
            </div>
            <div class="content">
              <div class="text">
                <el-skeleton :rows="5" animated />
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div class="chat-input">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          placeholder="请输入您对前端页面的问题..."
          :disabled="loading"
          @keydown.ctrl.enter="sendMessage"
        />
        <div class="input-actions">
          <el-button 
            type="primary" 
            @click="sendMessage"
            :disabled="!inputMessage.trim() || loading"
            :loading="loading"
          >
            发送 (Ctrl+Enter)
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, nextTick, watch } from 'vue'
import { Delete } from '@element-plus/icons-vue'
import qwenApi from '../api/qwenApi.js'
import { ElMessage } from 'element-plus'

const inputMessage = ref('')
const messages = ref([
  {
    role: 'assistant',
    content: '您好！我是通义灵码助手，您可以向我提问关于前端页面的任何问题。例如："如何优化这个系统的用户界面？" 或 "怎样实现一个分页功能？"'
  }
])
const loading = ref(false)
const chatContainer = ref(null)

// 格式化消息内容，处理代码块
const formatMessage = (content) => {
  // 转义HTML
  let formatted = content
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
  
  // 处理代码块
  formatted = formatted.replace(/```([\s\S]*?)```/g, '<pre><code>$1</code></pre>')
  
  // 处理行内代码
  formatted = formatted.replace(/`([^`]+)`/g, '<code>$1</code>')
  
  // 处理换行
  formatted = formatted.replace(/\n/g, '<br>')
  
  return formatted
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return
  
  const userMessage = {
    role: 'user',
    content: inputMessage.value.trim()
  }
  
  messages.value.push(userMessage)
  const userQuestion = inputMessage.value
  inputMessage.value = ''
  loading.value = true
  
  try {
    // 调用通义千问API
    const response = await qwenApi.chat({
      input: {
        messages: [
          ...getHistoryMessages(),
          {
            role: 'user',
            content: userQuestion
          }
        ]
      }
    })

    // 解析响应并添加助手回复
    if (response && response.output) {
      const assistantMessage = {
        role: 'assistant',
        content: response.output.text
      }
      messages.value.push(assistantMessage)
    } else {
      throw new Error('响应格式不正确')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('发送消息失败: ' + error.message)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，处理您的问题时出现错误，请稍后重试。'
    })
  } finally {
    loading.value = false
    scrollToBottom()
  }
}

// 获取历史消息（除了第一条欢迎消息）
const getHistoryMessages = () => {
  return messages.value
    .slice(1) // 排除第一条欢迎消息
    .map(msg => ({
      role: msg.role,
      content: msg.content
    }))
}

// 清空聊天记录
const clearChat = () => {
  messages.value = [
    {
      role: 'assistant',
      content: '您好！我是通义灵码助手，您可以向我提问关于前端页面的任何问题。例如："如何优化这个系统的用户界面？" 或 "怎样实现一个分页功能？"'
    }
  ]
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

// 监听加载状态变化
watch(loading, () => {
  scrollToBottom()
})
</script>

<style scoped>
.lingma-chat-container {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.chat-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  height: calc(100vh - 300px);
}

.message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  gap: 10px;
}

.message.user {
  text-align: right;
}

.message.user .message-content {
  flex-direction: row-reverse;
}

.message.user .content {
  background-color: #409eff;
  color: white;
}

.message.assistant .content {
  background-color: #f5f5f5;
}

.content {
  max-width: 80%;
  padding: 10px 15px;
  border-radius: 8px;
  text-align: left;
}

.content .text {
  white-space: pre-wrap;
  line-height: 1.5;
}

.content .text :deep(pre) {
  background-color: #2d2d2d;
  color: #f8f8f2;
  padding: 12px;
  border-radius: 4px;
  overflow-x: auto;
}

.content .text :deep(code) {
  background-color: #f0f0f0;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
}

.chat-input {
  margin-top: 20px;
}

.input-actions {
  margin-top: 10px;
  text-align: right;
}

/* 滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Firefox浏览器滚动条样式 */
.chat-messages {
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}
</style>